package com.harry.utility;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.internal.CriteriaImpl.Subcriteria;
import org.hibernate.internal.util.StringHelper;

/**
 * Hibernate - Criteria 实体转换算法工具类
 */
public class InnerCriteriaHelper {

	public static CriteriaImpl getImplFromDC(DetachedCriteria dc) throws Exception {
		Field implField = dc.getClass().getDeclaredField("impl");
		implField.setAccessible(true);
		CriteriaImpl impl = (CriteriaImpl) implField.get(dc);
		return impl;
	}

	public static Map<String, String> getTableAliasFromDC(DetachedCriteria target) throws Exception {
		CriteriaImpl impl = getImplFromDC(target);
		int subIndex = 1;
		Map<String, String> tableAliasMap = new HashMap<>();
		tableAliasMap.put("this", StringHelper.generateAlias("this", 0));
		for (Iterator<Subcriteria> it = impl.iterateSubcriteria(); it.hasNext(); subIndex++) {
			Subcriteria sub = it.next();
			tableAliasMap.put(sub.getAlias(), StringHelper.generateAlias(sub.getAlias(), subIndex));
		}
		return tableAliasMap;
	}

	private static Set<String> opSet = new HashSet<>();
	static {
		for (Method temp : Restrictions.class.getMethods()) {
			if (Pattern.matches(".+(Property)$", temp.getName())) {
				opSet.add(temp.getName().substring(0, temp.getName().length() - "Property".length()));
			}
		}
	}

	public static Set<String> operSet() {
		return opSet;
	}
}
